package com.agile.leetcode.url;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/7/8 17:05
 */
public class URLDownload {
    public static void main(String[] args) throws IOException {
        String path = "https://git.imweb.io/f1-t1/moments/raw/767f61a336e804e212161fca9af7975980b368ae/img/avatar-zhoujielun.png";
        String savePath = "E://pic";
        String fileName = "jay.jpg";
        URL url = new URL(path);
        // 打开连接
        URLConnection connection = url.openConnection();
        // 设置超时时间
        connection.setConnectTimeout(3 * 1000);
        InputStream inputStream = connection.getInputStream();
        // 创建缓冲区
        byte[] bytes = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }
        bos.close();
        byte[] getData = bos.toByteArray();
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File saveFile = new File(file, fileName);
        // 拿到文件输出流
        FileOutputStream fos = new FileOutputStream(saveFile);
        // 写文件
        fos.write(getData);
        fos.close();
        inputStream.close();
    }
}
